#!/bin/bash

################################################################################
# Tonys Director64 - GUI Launcher
# Shows status window with NCIS branding
################################################################################

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Check if in app bundle
if [[ "$SCRIPT_DIR" == *"/Contents/MacOS"* ]]; then
    RESOURCES_DIR="$SCRIPT_DIR/../Resources"
else
    RESOURCES_DIR="$SCRIPT_DIR"
fi

cd "$RESOURCES_DIR"

# Add Homebrew to PATH if it exists (for detection)
if [ -f "/opt/homebrew/bin/brew" ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f "/usr/local/bin/brew" ]; then
    eval "$(/usr/local/bin/brew shellenv)"
fi

# Check prerequisites
HOMEBREW_STATUS="❌ Not Installed"
WINE_STATUS="❌ Not Installed"
WINETRICKS_STATUS="❌ Not Installed"
FFMPEG_STATUS="❌ Not Installed"
QUICKTIME_STATUS="❌ Not Installed"

if command -v brew &> /dev/null; then
    HOMEBREW_STATUS="✅ Installed"
fi

if command -v wine &> /dev/null; then
    WINE_STATUS="✅ Installed"
fi

if command -v winetricks &> /dev/null; then
    WINETRICKS_STATUS="✅ Installed"
fi

if command -v ffmpeg &> /dev/null; then
    FFMPEG_STATUS="✅ Installed"
fi

# Set Wine prefix
# Set Wine prefix
export WINEPREFIX="$HOME/.wine"

# ==============================================================================
# LICENSING & PROTECTION SYSTEM
# ==============================================================================

# ----------------- CONFIGURATION -----------------
# [IMPORTANT]: CHANGE THIS URL TO YOUR WEB SERVER
API_URL="https://www.director64.com/activate_license.php"
# -------------------------------------------------

DATA_DIR="$HOME/.director64_data"
GAME_DIR="$DATA_DIR/game"
LICENSE_FILE="$DATA_DIR/license.json"
mkdir -p "$GAME_DIR"

check_internet() {
    ping -c 1 google.com &> /dev/null
}

get_hwid() {
    ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}'
}

extract_json_val() {
    python3 -c "import sys, json; print(json.load(sys.stdin)['$1'])" 2>/dev/null
}

activate_license() {
    while true; do
        # Prompt for Serial
        SERIAL_INPUT=$(osascript -e 'display dialog "Please enter your Serial Number to activate:" default answer "" with title "Director64 Verification" buttons {"Quit", "Activate"} default button "Activate" with icon note' 2>/dev/null)
        
        if echo "$SERIAL_INPUT" | grep -q "Quit"; then
            exit 0
        fi
        
        # Robust parsing: extract text between "text returned:" and the following comma (or end of line)
        SERIAL=$(echo "$SERIAL_INPUT" | sed -n 's/.*text returned:\([^,]*\).*/\1/p' | xargs)
        HWID=$(get_hwid)
        
        # Debug log
        echo "$(date): Attempting activation with Serial: [$SERIAL], HWID: [$HWID]" >> "$HOME/.director64_debug.log"
        
        # Show "Connecting..."
        osascript -e 'display notification "Verifying serial number..." with title "Director64 System"'
        
        RESPONSE=$(curl -s -k -X POST -d "serial_key=$SERIAL&hwid=$HWID" "$API_URL")
        echo "$(date): Server Response: $RESPONSE" >> "$HOME/.director64_debug.log"
        
        # Check Success
        IS_SUCCESS=$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('success', False))" 2>/dev/null)
        
        if [ "$IS_SUCCESS" == "True" ]; then
            # Save License
            echo "$RESPONSE" > "$LICENSE_FILE"
            
            # Get Manifest
            MANIFEST=$(echo "$RESPONSE" | python3 -c "import sys, json; print(','.join(json.load(sys.stdin).get('manifest', [])))")
            
            # Actual Download with Native Progress Bar
            osascript -e 'display dialog "Activation Successful!\n\nSecurely downloading game files...\nPlease wait." buttons {"OK"} default button "OK" give up after 2 with title "Director64 System"'
            
            # Start AppleScript Progress Bar in Background
            osascript -e 'set progress total steps to 100' -e 'set progress completed steps to 0' -e 'set progress description to "Securing Installation..." ' &
            
            # Core Download Loop (Bash is more reliable for this)
            IFS=',' read -ra ADDR <<< "$MANIFEST"
            TOTAL=${#ADDR[@]}
            COUNT=0
            
            for FILE_PATH in "${ADDR[@]}"; do
                COUNT=$((COUNT + 1))
                PERCENT=$(( (COUNT * 100) / TOTAL ))
                
                # Update Progress Bar
                osascript -e "set progress completed steps to $PERCENT" -e "set progress additional description to \"Downloading: $FILE_PATH ($COUNT/$TOTAL)\" " &>/dev/null
                
                # Ensure directory exists in hidden folder
                FILE_DIR=$(dirname "$FILE_PATH")
                mkdir -p "$GAME_DIR/$FILE_DIR"
                
                # Download file via secure proxy
                curl -s -k -X POST -d "action=download_file&serial_key=$SERIAL&hwid=$HWID&filename=$FILE_PATH" "$API_URL" -o "$GAME_DIR/$FILE_PATH"
                
                # Check if download actually worked
                if [ ! -s "$GAME_DIR/$FILE_PATH" ]; then
                    echo "$(date): FAILED to download $FILE_PATH" >> "$HOME/.director64_debug.log"
                fi
            done
            
            osascript -e 'display notification "All files secured!" with title "Director64 System"'
            
            # Security Cleanup
            rm -f "$RESOURCES_DIR/Director64_Dashboard.py" 2>/dev/null
            rm -f "$RESOURCES_DIR/DCR_Launcher_GUI_Shell.sh" 2>/dev/null
            
            osascript -e 'display dialog "Installation Complete." buttons {"Start"} default button 1 with title "Director64 System"'
            break
        else
            MSG=$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('message', 'Unknown Error'))" 2>/dev/null)
            osascript -e "display dialog \"Activation Failed:\n$MSG\" buttons {\"Try Again\", \"Quit\"} with icon stop with title \"Error\""
            if [ $? -ne 0 ]; then exit 0; fi
        fi
    done
}

# --- MAIN LICENSE CHECK ---
if [ -f "$LICENSE_FILE" ]; then
    # Validate Time Bomb (Local Check)
    EXP_TS=$(cat "$LICENSE_FILE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('expiration_timestamp') or 0)" 2>/dev/null)
    
    if [ "$EXP_TS" != "0" ] && [ "$EXP_TS" != "None" ]; then
        NOW=$(date +%s)
        if [ "$NOW" -gt "$EXP_TS" ]; then
            EXP_DATE=$(date -r "$EXP_TS")
            RESULT=$(osascript -e "display dialog \"LICENSE EXPIRED\n\nYour license expired on: $EXP_DATE\n\nPlease enter a new serial number.\" buttons {\"Quit\", \"Enter New Key\"} default button \"Enter New Key\" with icon stop" 2>/dev/null)
            
            if echo "$RESULT" | grep -q "Enter New Key"; then
                # Remove expired license and re-activate
                rm -f "$LICENSE_FILE"
                activate_license
            else
                exit 0
            fi
        fi
    fi
    
    # Check if files actually exist (deleted?)
    # Be more lenient: check if the directory contains ANYTHING at all
    if [ ! -d "$GAME_DIR" ] || [ -z "$(ls -A "$GAME_DIR" 2>/dev/null)" ]; then
         osascript -e 'display dialog "Game files missing. Re-activation required." buttons {"OK"}'
         activate_license
    fi
else
    # No license found
    activate_license
fi

# Check if QuickTime is installed in Wine
if [ -d "$WINEPREFIX/drive_c/windows/system32/QuickTime" ] || \
   [ -f "$WINEPREFIX/drive_c/windows/system32/qtmlClient.dll" ] || \
   [ -d "$WINEPREFIX/drive_c/Program Files/QuickTime" ] || \
   [ -d "$WINEPREFIX/drive_c/Program Files (x86)/QuickTime" ]; then
    QUICKTIME_STATUS="✅ Installed"
fi

# Find files for launch (quietly)
# 1. First, look for a bundled projector in the App's Resources
# We check the original RESOURCES_DIR we found at startup
APP_BUNDLED_PROJECTOR=$(find "$RESOURCES_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)

if [ -n "$APP_BUNDLED_PROJECTOR" ]; then
    # If we found it in the app bundle, copy it (and all supporting DLLs/Xtras) to the hidden GAME_DIR
    # This is critical so the projector can see the downloaded .dcr files
    PROJ_DIR=$(dirname "$APP_BUNDLED_PROJECTOR")
    cp -rn "$PROJ_DIR/"* "$GAME_DIR/" 2>/dev/null
fi

# 2. Now find the projector to run (preferring the copy in the hidden dir)
PROJECTOR=$(find "$GAME_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)

if [ -z "$PROJECTOR" ]; then
    PROJECTOR=$(find "$GAME_DIR" -maxdepth 2 -iname "*.exe" -type f 2>/dev/null | head -n 1)
fi

# Build status message with NCIS branding
STATUS_MSG="Tonys Director64 v4.2
Director64.com

WARNING:
H.264 video will NOT play.
Please deliver movies in MPEG-4 (.mov).
(A Video Converter tool is available below)

System Requirements:

• Homebrew:   $HOMEBREW_STATUS
• Wine:       $WINE_STATUS
• Winetricks: $WINETRICKS_STATUS
• FFmpeg:     $FFMPEG_STATUS
• QuickTime:  $QUICKTIME_STATUS

Questions or comments?
Email: tony@mushamel.com"

# Function to check if all core requirements are met
check_core_requirements() {
    command -v brew &> /dev/null && \
    command -v wine &> /dev/null && \
    command -v ffmpeg &> /dev/null
}

# Function to check if QuickTime is installed
check_quicktime() {
    [ -d "$WINEPREFIX/drive_c/windows/system32/QuickTime" ] || \
    [ -f "$WINEPREFIX/drive_c/windows/system32/qtmlClient.dll" ] || \
    [ -d "$WINEPREFIX/drive_c/Program Files/QuickTime" ] || \
    [ -d "$WINEPREFIX/drive_c/Program Files (x86)/QuickTime" ]
}

# Function to run uninstall wizard
run_uninstall_wizard() {
    # Confirm uninstall
    CONFIRM=$(osascript -e 'display dialog "Are you sure you want to uninstall?\n\nThis will remove:\n• Wine\n• Winetricks\n• QuickTime\n• Wine data\n\nOptionally also Homebrew." buttons {"Cancel", "Uninstall"} default button "Cancel" with title "Confirm Uninstall"' 2>/dev/null 2>&1)
    
    if echo "$CONFIRM" | grep -q "Uninstall"; then
        # Create uninstall script
        TEMP_SCRIPT="/tmp/uninstall_ncis.sh"
        cat > "$TEMP_SCRIPT" << 'SCRIPT_EOF'
#!/bin/bash
clear
echo "╔════════════════════════════════════════════════════════════╗"
echo "║      Uninstall Wine, Winetricks, FFmpeg & QuickTime        ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Add Homebrew to PATH
if [ -f /opt/homebrew/bin/brew ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f /usr/local/bin/brew ]; then
    eval "$(/usr/local/bin/brew shellenv)"
fi

echo "🗑️  Uninstalling Winetricks..."
brew uninstall winetricks 2>/dev/null
echo "✓ Winetricks uninstalled"

echo ""
echo "🗑️  Uninstalling FFmpeg..."
brew uninstall ffmpeg 2>/dev/null
echo "✓ FFmpeg uninstalled"

echo ""
echo "🗑️  Uninstalling Wine..."
brew uninstall --cask wine-stable 2>/dev/null
brew uninstall --cask wine-crossover 2>/dev/null
echo "✓ Wine uninstalled"

echo ""
echo "🗑️  Removing Wine data (includes QuickTime)..."
rm -rf ~/.wine
echo "✓ Wine data removed"

echo ""
echo "🗑️  Removing Wine app..."
sudo rm -rf "/Applications/Wine Stable.app" 2>/dev/null
echo "✓ Wine app removed"

echo ""
echo "🗑️  Removing Winetricks cache..."
rm -rf ~/.cache/winetricks 2>/dev/null
echo "✓ Winetricks cache removed"

echo ""
read -p "Also uninstall Homebrew? [y/N]: " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo ""
    echo "🗑️  Uninstalling Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh)"
    
    echo ""
    echo "Cleaning up Homebrew directories..."
    sudo rm -rf /opt/homebrew 2>/dev/null
    sudo rm -rf /usr/local/Homebrew 2>/dev/null
    echo "✓ Homebrew removed"
fi

echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║          ✅ Uninstall Complete!                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo "Close this window."
echo ""
read -p "Press Enter to close..."
SCRIPT_EOF
        
        chmod +x "$TEMP_SCRIPT"
        open -a Terminal "$TEMP_SCRIPT"

        osascript -e 'display dialog "Uninstall started in Terminal.\n\nFollow the prompts to complete the uninstall.\n\nWhen finished, close Terminal." buttons {"OK"} default button "OK" with title "Tonys Director64"'
        exit 0
    fi
    # Re-run menu if canceled (or just exit if called from main)
    exit 0
}

# Check if all ready (including QuickTime)
if check_core_requirements; then
    
    # Check if QuickTime is missing
    if ! check_quicktime; then
        STATUS_MSG="$STATUS_MSG

⚠️ QuickTime not installed!
Video playback may not work."
        
        RESULT=$(osascript -e "display dialog \"$STATUS_MSG\" buttons {\"Uninstall\", \"Video Converter\", \"Install QuickTime\"} default button \"Install QuickTime\" with title \"Tonys Director64\"" 2>&1)
        
        if echo "$RESULT" | grep -q "Video Converter"; then
            open -a Terminal "$RESOURCES_DIR/Video_Converter.sh"
            exit 0
        elif echo "$RESULT" | grep -q "Install QuickTime"; then
            # Install QuickTime via winetricks
            TEMP_SCRIPT="/tmp/install_quicktime.sh"
            cat > "$TEMP_SCRIPT" << 'SCRIPT_EOF'
#!/bin/bash
clear
echo "========================================"
echo "  Installing QuickTime for Wine"
echo "========================================"
echo ""

# Load Homebrew
if [ -f /opt/homebrew/bin/brew ]; then 
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f /usr/local/bin/brew ]; then 
    eval "$(/usr/local/bin/brew shellenv)"
fi

# Install winetricks if not present
if ! command -v winetricks &> /dev/null; then
    echo "Installing winetricks..."
    brew install winetricks
    echo ""
fi

echo "Installing QuickTime 7.2 via winetricks..."
echo "(This may take a few minutes)"
echo ""

# Set Wine prefix
export WINEPREFIX="$HOME/.wine"

# Install QuickTime using winetricks
winetricks -q quicktime72

echo ""
echo "========================================"
echo "  ✅ QuickTime Installed!"
echo "========================================"
echo ""
echo "Close this window and reopen the app."
echo ""
read -p "Press Enter to close..."
SCRIPT_EOF
            
            chmod +x "$TEMP_SCRIPT"
            open -a Terminal "$TEMP_SCRIPT"
            
            osascript -e 'display dialog "QuickTime installation started in Terminal.\n\nPlease wait for installation to complete.\n\nWhen you see \"QuickTime Installed!\", close Terminal and reopen this app." buttons {"OK"} default button "OK" with title "Tonys Director64"'
            exit 0
        elif echo "$RESULT" | grep -q "Uninstall"; then
            run_uninstall_wizard
            exit 0
        else
            exit 0
        fi
    else
        # All requirements met!
        # Your system's Python/Tkinter is currently reporting a version mismatch error.
        # To ensure 100% reliability, we will use the native macOS dialog system.
        
        # Main Dashboard
        RESULT_LEGACY=$(osascript -e "display dialog \"$STATUS_MSG\" buttons {\"Tools\", \"Quit\", \"Launch\"} default button \"Launch\" with title \"Tonys Director64\"" 2>&1)
        
        if echo "$RESULT_LEGACY" | grep -q "Launch"; then
            RESULT="ACTION:LAUNCH"
        elif echo "$RESULT_LEGACY" | grep -q "Tools"; then
            # Secondary dialog for tools
            TOOL_CHOICE=$(osascript -e "display dialog \"Maintenance Tools:\n\nSelect a utility to run:\" buttons {\"Back\", \"Uninstall\", \"Video Converter\"} default button \"Video Converter\" with title \"Director64 Tools\"" 2>&1)
            if echo "$TOOL_CHOICE" | grep -q "Uninstall"; then
                RESULT="ACTION:UNINSTALL"
            elif echo "$TOOL_CHOICE" | grep -q "Video Converter"; then
                RESULT="ACTION:CONVERT"
            else
                exec "$0" # Go back to main
            fi
        else
            exit 0 # User clicked Quit
        fi

        if [[ "$RESULT" == *"ACTION:UNINSTALL"* ]]; then
            run_uninstall_wizard
            # Re-run menu if canceled
            exec "$0"
        elif [[ "$RESULT" == *"ACTION:CONVERT"* ]]; then
             open -a Terminal "$RESOURCES_DIR/Video_Converter.sh"
             exit 0
        elif [[ "$RESULT" == *"ACTION:LAUNCH"* ]]; then
             # fall through to launch logic below
             :
        else
             exit 0 # Quitting
        fi
    fi

    if echo "$RESULT" | grep -q "Launch" || [[ "$RESULT" == *"ACTION:LAUNCH"* ]]; then
        # Kill any existing Wine processes
        pkill -9 wine 2>/dev/null
        pkill -9 wineserver 2>/dev/null
        pkill -9 winedevice 2>/dev/null
        sleep 1
        
        if [ -z "$PROJECTOR" ]; then
            osascript -e 'display dialog "LAUNCH ERROR:\n\nNo executable (.exe) found in the game folder.\n\nPlease check your server payload folder content." buttons {"OK"} with icon stop'
            exit 1
        fi
        
        # Determine absolute paths (with fallbacks to prevent errors)
        PROJECTOR_ABS=$(realpath "$PROJECTOR" 2>/dev/null || echo "$PROJECTOR")
        
        # Initialize Wine prefix if needed
        export WINEPREFIX="$HOME/.wine"
        if [ ! -d "$WINEPREFIX/drive_c" ]; then
            wineboot -u &>/dev/null
            sleep 2
        fi
        
        # Launch Wine with the DCR file
        # IMPORTANT: CD into the projector dir so it finds its own DLLs/Xtras
        cd "$(dirname "$PROJECTOR_ABS")" || exit 1
        wine "$(basename "$PROJECTOR_ABS")" &>/dev/null &
        
        # Wait for window to appear, then maximize it
        sleep 3
        osascript -e 'tell application "System Events" to tell process "Wine" to set frontmost to true' 2>/dev/null
        osascript -e 'tell application "System Events" to keystroke "f" using {control down, command down}' 2>/dev/null
    fi
else
    # Something missing
    STATUS_MSG="$STATUS_MSG

⚠️ Missing prerequisites"
    
    # Determine what to install
    if ! command -v brew &> /dev/null; then
        RESULT=$(osascript -e "display dialog \"$STATUS_MSG\" buttons {\"Uninstall\", \"Quit\", \"Install All\"} default button \"Install All\" with title \"Tonys Director64\"" 2>&1)
        
        if echo "$RESULT" | grep -q "Install All"; then
            # Create a temporary script to run in Terminal
            TEMP_SCRIPT="/tmp/install_ncis_deps.sh"
            cat > "$TEMP_SCRIPT" << 'SCRIPT_EOF'
#!/bin/bash
clear
echo "========================================"
echo "  Tonys Director64 Setup"
echo "========================================"
echo ""
echo "Step 1/5: Installing Homebrew..."
echo ""
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
echo ""
echo "========================================"
echo "Step 2/5: Installing Wine..."
echo "========================================"
echo ""
if [ -f /opt/homebrew/bin/brew ]; then 
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f /usr/local/bin/brew ]; then 
    eval "$(/usr/local/bin/brew shellenv)"
fi
brew tap gcenx/wine
brew install --cask wine-crossover
echo ""
echo "Removing security quarantine..."
sudo xattr -rd com.apple.quarantine /Applications/Wine\ Stable.app 2>/dev/null
echo ""
echo "========================================"
echo "Step 3/5: Installing Winetricks..."
echo "========================================"
echo ""
brew install winetricks
echo ""
echo "========================================"
echo "Step 4/5: Installing FFmpeg..."
echo "========================================"
echo ""
brew install ffmpeg
echo ""
echo "========================================"
echo "Step 5/5: Installing QuickTime..."
echo "========================================"
echo ""
echo "Initializing Wine prefix..."
export WINEPREFIX="$HOME/.wine"
wineboot -u 2>/dev/null
sleep 3
echo ""
echo "Installing QuickTime 7.2 via winetricks..."
echo "(This may take a few minutes)"
winetricks -q quicktime72
echo ""
echo "========================================"
echo "  ✅ Installation Complete!"
echo "========================================"
echo ""
echo "Close this window and reopen the app."
echo ""
read -p "Press Enter to close..."
SCRIPT_EOF
            
            chmod +x "$TEMP_SCRIPT"
            open -a Terminal "$TEMP_SCRIPT"
            
            osascript -e 'display dialog "Installation started in Terminal.\n\n⏱️ First-time setup may take 10-20 minutes.\n\nThis will install:\n• Apple Command Line Tools (if needed)\n• Homebrew\n• Wine (via gcenx tap)\n• Winetricks\n• FFmpeg\n• QuickTime\n\nPlease follow the prompts in Terminal.\nWhen you see \"Installation Complete!\", close Terminal and reopen this app." buttons {"OK"} default button "OK" with title "Tonys Director64"'
        elif echo "$RESULT" | grep -q "Uninstall"; then
            run_uninstall_wizard
            exit 0
        fi
    elif ! command -v wine &> /dev/null || ! command -v ffmpeg &> /dev/null; then
        RESULT=$(osascript -e "display dialog \"$STATUS_MSG\" buttons {\"Uninstall\", \"Quit\", \"Install Dependencies\"} default button \"Install Dependencies\" with title \"Tonys Director64\"" 2>&1)
        
        if echo "$RESULT" | grep -q "Install Dependencies"; then
            # Create a temporary script to run in Terminal
            TEMP_SCRIPT="/tmp/install_wine.sh"
            cat > "$TEMP_SCRIPT" << 'SCRIPT_EOF'
#!/bin/bash
clear
echo "========================================"
echo "  Installing Dependencies"
echo "========================================"
echo ""
echo "Loading Homebrew..."
if [ -f /opt/homebrew/bin/brew ]; then 
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f /usr/local/bin/brew ]; then 
    eval "$(/usr/local/bin/brew shellenv)"
fi
echo ""
echo "Step 1/4: Installing Wine..."
echo ""
brew tap gcenx/wine
brew install --cask wine-crossover
echo ""
echo "Removing security quarantine..."
sudo xattr -rd com.apple.quarantine /Applications/Wine\ Stable.app 2>/dev/null
echo ""
echo "========================================"
echo "Step 2/4: Installing Winetricks..."
echo "========================================"
echo ""
brew install winetricks
echo ""
echo "========================================"
echo "Step 3/4: Installing FFmpeg..."
echo "========================================"
echo ""
brew install ffmpeg
echo ""
echo "========================================"
echo "Step 4/4: Installing QuickTime..."
echo "========================================"
echo ""
echo "Initializing Wine prefix..."
export WINEPREFIX="$HOME/.wine"
wineboot -u 2>/dev/null
sleep 3
echo ""
echo "Installing QuickTime 7.2 via winetricks..."
echo "(This may take a few minutes)"
winetricks -q quicktime72
echo ""
echo "========================================"
echo "  ✅ Installation Complete!"
echo "========================================"
echo ""
echo "Close this window and reopen the app."
echo ""
read -p "Press Enter to close..."
SCRIPT_EOF
            
            chmod +x "$TEMP_SCRIPT"
            open -a Terminal "$TEMP_SCRIPT"
            
            osascript -e 'display dialog "Installation started in Terminal.\n\n⏱️ This may take 5-10 minutes.\n\nThis will install:\n• Wine\n• Winetricks\n• FFmpeg\n• QuickTime\n\nWhen you see \"Installation Complete!\", close Terminal and reopen this app." buttons {"OK"} default button "OK" with title "Tonys Director64"'
        elif echo "$RESULT" | grep -q "Uninstall"; then
            run_uninstall_wizard
            exit 0
        fi
    else
        RESULT=$(osascript -e "display dialog \"$STATUS_MSG\" buttons {\"Uninstall\", \"OK\"} default button \"OK\" with title \"Tonys Director64\"" 2>&1)
        if echo "$RESULT" | grep -q "Uninstall"; then
            run_uninstall_wizard
            exit 0
        fi
    fi
fi

exit 0
